<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery.min.js"></script>
    <script src="js/template-web.js"></script>
    <script type="text/html" id="tem">
        <% for (var i = 0 ; i < comments.length ; i++) { %>
            <div class="cell">
                <p class="floor"><%= comments[i].id %>楼 <a href="" class="delete">删除</a></p>
                <p class="user-name">层主：<%= comments[i].username %></p>
                <p class="content"><%= comments[i].content %></p>
                <hr>
            </div>
        <% } %>
    </script>
</head>
<body>
    <div class="box">
        <div class="post">
            <h3>新年快乐</h3>
            <p>楼主： 行痴</p>
            <p>新的一年祝大家新年快乐，身体健康，升职加薪</p>
        </div>
        <hr>
        <div class="repeat">
            <div class="comment">
                <p>发表回复</p>
                <span>用户名：</span><input type="text">
                <textarea name="" id="" cols="30" rows="10"></textarea>
                <input type="button" value="评论" id="btn">
                <hr>
            </div>
            <div class="comment-list">
            </div>
        </div>
    </div>
    <script>
const $commentList = $(".comment-list");
$.get("http://localhost:3000/db",null,function (data) {
    const str = template('tem',data);
    $(str).appendTo($commentList);
    deleteData()
})
const $btn = $("#btn");
$btn.click(function () {
    const userName = $(":text").val(), content = $("textarea").val();
    if (userName && content) {
        $.post("http://localhost:3000/comments",{
            "username": userName,
            "content": content
        }, function (data) {
            const tepData = {"comments": [data]}//造一个符合板字符串语句的数据
            const str = template("tem", tepData);
            $(str).appendTo($commentList)
            deleteData();
        })
    $(":text").val("");
    $("textarea").val("");
    } else {
        alert("用户名或内容不能为空")
    }
})
function deleteData () {
    const $delete = $(".delete");//加载之后才能获取到，所以写在这里
    $delete.click(function () {
        const $cell = $(this).parents(".cell");
        console.log($cell)
        const idx = $cell.index() + 1;
        console.log(idx)
        $.ajax({
            url:"http://localhost:3000/comments/" + idx,
            type: "delete"
        })
        $cell.remove()
        return false;
    })
}
    </script>
</body>
</html>